class cart {
    constructor() {
        this.getCartGoods();
        //>给.list-body绑定点击事件,实现委托
        this.$('.list-body').addEventListener('click', this.dispatch);
        //>给全选按钮绑定点击事件
        this.$('.col-one-check input').addEventListener('click', this.checlkAll)

        //>结算绑定点击事件
        this.$('.btn-a').addEventListener('click', this.jieSuan)
    }

    //>购物车点击清除
    jieSuan = (tar) => {
        let self = this
        // console.log(111);
        layer.confirm('确认是否结算', {
            title: '结算提示框'
        }, function () {
            // console.log(self.$('.item-box'));
            self.$('.list-item').forEach((res) => {
                // console.log(self.$('.list-body'));
                console.log(res);
                let r = res;
                console.log( r.dataset.id);
                let fxk = res.querySelector('.icon-checkbox')
                // console.log(fxk);
                if (fxk.checked) {
                    const AUTH_TOKEN = localStorage.getItem('token')
                    axios.defaults.headers.common['authorization'] = AUTH_TOKEN;
                    let res = axios.get('http://localhost:8888/cart/remove', {
                        params: {
                            id: localStorage.getItem('user_id'),
                            goodsId: r.dataset.id
                        }
                    }).then(res1 => {
                        console.log(res1);
                        layer.closeAll()
                        r.remove()
                        location.reload()
                    })
                }
            })
        })

    }

    //>事件委托的分发
    dispatch = (eve) => {
        // console.log(this);
        //事件源的获取
        let target = eve.target;
        // console.log(target);
        //判断当前点击的是a标签
        if (target.nodeName == 'A' && target.classList.contains('del')) this.delGoodsData(target)
        //判断当前点击的是否为+操作
        if (target.nodeName == 'A' && target.classList.contains('plus')) this.plusGoodsNum(target);
        if (target.nodeName == 'A' && target.classList.contains('plus1')) this.plusGoodsNum(target);
    }

    //> + - 数量增加 减少的方法
    plusGoodsNum = (tar) => {
        // console.log(tar);
        let div = tar.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode;
        // console.log(div);
        //获取数量,单价和小计
        let num = div.querySelector('.goods-num');
        let sum = div.querySelector('.col-total');
        let price = div.querySelector('.col-price').innerHTML - 0;
        // console.log(num,sum,price);
        // 获取数量
        let numVal = num.value;
        //对数量进行加1 操作
        if (tar.className == 'plus') numVal++;
        if (tar.className == 'plus1') numVal--;
        // console.log(num);
        //更新input中的数量
        //给服务器发送数据,增加数量
        const AUTH_TOKEN = localStorage.getItem('token')
        axios.defaults.headers.common['authorization'] = AUTH_TOKEN;
        axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        let uId = localStorage.getItem('user_id');
        let gId = div.dataset.id;
        let param = `id=${uId}&&goodsId=${gId}&number=${numVal}`
        axios.post('http://localhost:8888/cart/number', param).then(res => {
            // console.log(res);
            let { status, data } = res;
            if (status == 200 && data.code == 1) {
                //将数量设置回去
                num.value = numVal;
                sum.innerHTML = parseInt(numVal * price * 100) / 100;
                this.countSumPrice();
            }
        })
    }

    //>全选的实现
    checlkAll = (eve) => {
        // console.log(this);
        //点击全选的时候让单个商品的选中框,跟随全选
        let allStatus = eve.target.checked;
        // console.log(allStatus);
        this.oneCheckGoods(allStatus);
        //调用统计数量和价格的方法
        this.countSumPrice();
    }
    //>让单个商品跟随全选状态
    oneCheckGoods(status) {
        // console.log(this.$('.iconfont'));
        if (this.$('.iconfont').length > 2) {
            this.$('.iconfont').forEach(input => {
                input.checked = status
            })
        } else {
            this.$('.iconfont').checked = status;
        }

    }
    //>单选的实现
    oneGoodCheckBox = () => {
        // console.log(this.$('.iconfont'));
        //给每个单选按钮绑定点击事件
        let self = this; //!保存this的指向
        if (this.$('.inputone').length > 2) {
            this.$('.inputone').forEach(input => {
                // console.log(self);
                input.onclick = function () {
                    //获取当前点击状态
                    // console.log(self);
                    //判断当前input点击的是取消,则取消全选
                    if (!this.checked) {
                        // console.log(self.$('.col-check input'));
                        self.$('.col-one-check input').checked = false;
                    }
                    //点击选中时,判断页面中是否有其他的未选中
                    if (this.checked) {
                        let status = self.getOneGoodsStatus();
                        // console.log(status);
                        self.$('.col-one-check input').checked = status;
                    }
                    //统计价格和数量
                    self.countSumPrice();
                }
            })
        } else {
            this.$('.inputone').onclick = () => {
                // 获取全选框的状态
                this.$('.col-one-check input').checked = this.$('.inputone').checked;

            }
        }

    }
    //>获取单个商品的选中状态
    getOneGoodsStatus() {
        // console.log(this.$('.iconfont'));
        //寻找是否有没选中的,如果页面中res为空数组
        let res = Array.from(this.$('.inputone')).find(input => {
            //  console.log(!input.checked);
            return !input.checked
        })
        // console.log(!res);
        // 如果res有值,则页面有没被选中的
        return !res;
    }
    //>统计数量和价格
    countSumPrice() {
        //*累加起来
        let sum = 0;
        let num = 0;
        //只统计选中商品
        if (this.$('.inputone').length > 2) {
            this.$('.inputone').forEach(input => {
                // console.log(input);
                if (input.checked) {
                    //通过input:checkbox 找到item-box
                    let div = input.parentNode.parentNode.parentNode;
                    // console.log(div);
                    //获取数量和小计
                    let tmpNum = div.querySelector('.goods-num').value - 0;
                    let tmpSum = div.querySelector('.col-total').innerHTML - 0;
                    // console.log(tmpNum,tmpSum);
                    sum += tmpSum;
                    num += tmpNum;

                }
            });
        } else {
            let input = this.$('.inputone')
            if (input.checked) {
                //通过input:checkbox 找到item-box
                let div = input.parentNode.parentNode.parentNode;
                // console.log(div);
                //获取数量和小计
                let tmpNum = div.querySelector('.goods-num').value - 0;
                let tmpSum = div.querySelector('.col-total').innerHTML - 0;
                // console.log(tmpNum,tmpSum);
                sum += tmpSum;
                num += tmpNum;

            }
        }

        //>保留小数点两位
        sum = parseInt(sum * 100) / 100;
        // console.log(sum,num);
        // 将数量和价格放在页面中
        this.$('.cart-total  i').innerHTML = num;
        this.$('.total-price em').innerHTML = sum;

    }

    //>删除购物车商品需要用户id和商品id
    delGoodsData(tar) {
        // console.log(tar);
        // console.log(id);
        //弹出框,询问是否删除
        let shanChu = layer.confirm('是否删除商品', {
            title: '删除提示框'
        }, function () {
            // console.log(111);
            // 确认的回调函数
            // 1.给后台发送数据,删除记录
            //找到商品id
            let div = tar.parentNode.parentNode.parentNode.parentNode.parentNode
            //    console.log(div);
            let gId = div.dataset.id;
            // console.log(gId);
            let uId = localStorage.getItem('user_id')
            // console.log(gId,uId);
            //发送数据请求
            //必须携带token,后台验证
            const AUTH_TOKEN = localStorage.getItem('token')
            axios.defaults.headers.common['authorization'] = AUTH_TOKEN;
            axios.get('http://localhost:8888/cart/remove', {
                params: {
                    id: uId,
                    goodsId: gId
                }
            }).then(res => {
                // console.log(res);
                layer.close(shanChu)
                div.firstElementChild.remove()
            })
        })


    }

    //>取出商品信息
    async getCartGoods() {
        //必须携带token,后台验证
        const AUTH_TOKEN = localStorage.getItem('token')
        axios.defaults.headers.common['authorization'] = AUTH_TOKEN;
        let { data, status } = await axios.get('http://localhost:8888/cart/list', {
            params: {
                id: localStorage.getItem('user_id')
            }
        })
        // console.log(res);
        //判断ajax的请求状态
        if (status == 200 && data.code == 1) {
            let html = '';
            data.cart.forEach(goods => {
                // console.log(goods);
                html += `
            <div data-v-33432b6e="" class="list-item" data-id="${goods.goods_id}">

                <div data-v-33432b6e="" class="item-box">
                    <div data-v-33432b6e="" class="item-table">
                        <div data-v-33432b6e="" class="item-row clearfix">
                            <div data-v-33432b6e="" class="col col-check"><input type='checkbox' data-v-33432b6e=""
                                    class="iconfont inputone icon-checkbox icon-checkbox-selected"></input>
                            </div>
                            <div data-v-33432b6e="" class="col col-img"><a data-v-33432b6e=""
                                    href="javascript:void(0)"><img data-v-33432b6e="" alt=""
                                        src="${goods.img_small_logo}"
                                        width="80" height="80"></a></div>
                            <div data-v-33432b6e="" class="col col-name">
                                <div data-v-33432b6e="" class="tags">

                                </div>

                                <h3 data-v-33432b6e="" class="name"><a data-v-33432b6e=""
                                        href="javascript:void(0)">${goods.title}</a></h3>

                            </div>
                            <div data-v-33432b6e="" class="col col-price">${goods.current_price}
                            </div>
                            <div data-v-33432b6e="" class="col col-num">
                                <div data-v-33432b6e="" class="change-goods-num clearfix">
                                <a data-v-33432b6e="" href="javascript:void(0)" class='plus1'>-</a>
                                <input
                                        data-v-33432b6e="" type="text" value="${goods.cart_number}" autocomplete="off"
                                        class="goods-num">
                                        <a data-v-33432b6e=""href="javascript:void(0)" class="plus">+</a>

                                </div>
                            </div>
                            <div data-v-33432b6e="" class="col col-total">
                            ${goods.current_price * goods.cart_number}
                            </div>
                            <div data-v-33432b6e="" class="col col-action"><a data-v-33432b6e="" data-v-33432b6e=""
                                    href="javascript:void(0);" title="删除" class="del">x</a></div>
                        </div>
                    </div>

                </div>`

            });
            //>将拼接好的字符串追加到页面中
            this.$('.list-body').innerHTML += html;
            //!单个商品的追加是异步实现的 所以单选按钮事件绑定要放在追加的页面下面  
            this.oneGoodCheckBox();
        }
        //登录过期的处理
        if (status == 200 && data.code == 401) {
            //登录过期,重新登录
            //清除local中的token和userid
            localStorage.removeItem('token');
            localStorage.removeItem('user_id')
            //跳转登录页面
            location.assign('./login.html?returnUrl=./cart2.html')

        }



    }


    // > 封装获取节点的方法
    $(ele) {
        let res = document.querySelectorAll(ele)
        // 如果获取到的是,当个节点的集合,就返回单个节点,如果多个集合就返回多个
        return res.length == 1 ? res[0] : res;
    }
};
new cart();